package com.yb0os1.decorator.springtest;

import org.springframework.context.ApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.Map;

public class TimestampRequestResponseBodyMethodProcessor implements HandlerMethodArgumentResolver {
    private RequestResponseBodyMethodProcessor processor;
    private ApplicationContext applicationContext;


    public TimestampRequestResponseBodyMethodProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(TimestampRequestBody.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        setupProcessor();
        Object o = processor.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
        if (!(o instanceof Map<?,?>)){
            return o;
        }
        Map<String,Object> map = (Map<String,Object>) o;
        map.put("timestamp",System.currentTimeMillis());
        return map;
    }

    private void setupProcessor() {
        if (processor != null){
           return;
        }
        RequestMappingHandlerAdapter adapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
        for (HandlerMethodArgumentResolver argumentResolver : adapter.getArgumentResolvers()) {
            if (argumentResolver instanceof RequestResponseBodyMethodProcessor){
                processor = (RequestResponseBodyMethodProcessor) argumentResolver;
                break;
            }
        }
    }
}
